<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Production extends CI_Controller {

	function __construct(){
		parent::__construct();
		authRedirect('/admin/index');
		$this->load->model('production_model');
	}
	public function index()
	{
		$data['error'] = $this->session->flashdata('error');
		$data['success'] = $this->session->flashdata('success');

		$data['production'] = $this->production_model->get_production();
		$this->load->view('admin/production/list.tpl',$data);
	}

	public function action(){
		$data['error'] = $this->session->flashdata('error');
		$data['success'] = $this->session->flashdata('success');

		$this->load->library('form_validation');
		if ($this->form_validation->run('add_production')) {
			$r = $this->production_model->add_production();
			if($r['status']){
				$this->session->set_flashdata('success','商品添加成功！');
				redirect('/admin/production');
			}else{
				$this->session->set_flashdata('error',$r['msg']);
				redirect('/admin/production/action');
			}
		}else{
			$data['error'] = validation_errors();
		}
		
		$data['p'] = '';
		$data['action'] = '/admin/production/action';
		$data['button'] = '增加商品';
		if((int)$this->uri->segment(4)){
			$data['p'] = $this->production_model->get_production_byid((int)$this->uri->segment(4));
			$data['action'] = '/admin/production/update/' . (int)$this->uri->segment(4);
			$data['button'] = '更新商品';
		}
		$this->load->model('toolimage_model');
		if (isset($data['p']->image) && $data['p']->image && file_exists(DIR_IMAGE . $data['p']->image)) {
			$data['preview'] = $this->toolimage_model->resize($data['p']->image, 100, 100);
		} else {
			$data['preview'] = $this->toolimage_model->resize('no_image.jpg', 100, 100);
		}
		$this->load->view('admin/production/action.tpl',$data);
	}

	public function update(){
		$id = (int)$this->uri->segment(4);
		if(!$id) show_error('错误的操作');

		$p = $this->production_model->get_production_byid($id);
		if(!$p) show_error('该商品可能已经被删除');

		$this->load->library('form_validation');
		if($this->form_validation->run('add_production')){
			$r = $this->production_model->update($id);
			if($r['status']){
				$this->session->set_flashdata('success','更新成功！');
				redirect('/admin/production');
			}else{
				$this->session->set_flashdata('error',$r['msg']);
				redirect('/admin/production/action/' . $id);
			}
		}else{
			$this->session->set_flashdata('error',validation_errors());
			redirect('/admin/production/action/' . $id);
		}
	}
}

/* End of file production.php */
/* Location: ./application/controllers/admin/production.php */